(function($) {
    $.fn.autoLocation = function(onSelectedCallback) {
        var locationElement = $(this);
        var emptyTip = i18n('LABEL_ENTER_LOCATION_TIP'); 

        var validLocations = pwc.locationCache.getAllValidFullNames();
        locationElement.autocomplete(validLocations, {
            mustMatch: false,
            matchContains: true,       
            width: 168,
            cacheLength: 10,
            matchSubset: true,
            // TW PwC team modify the jquery.autocomplete.js file, to make it support multiKeyword and moMatchFoundMessage
            multiKeyword: true,
            noMatchFoundMessage: i18n("ERROR_NO_MATCH_LOCATION"),
            highlight: function(value, term) {
                var result = value;
                $(term.split(' ')).each(function() {
                    result = result.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + this.replace(/([\^\$\(\)\[\]\{\}\*\.\+\?\|\\])/gi, "\\$1") + ")(?![^<>]*>)(?![^&;]+;)", "gi"), "<strong>$1</strong>");
                });
                return result;
            }
        });

        locationElement.result(function() {
            if ($.isFunction(onSelectedCallback)) {
                onSelectedCallback();
            }
        });

        locationElement.change(function() {
            $(this).search();
        });

        locationElement.blur(function() {
            addTipIfEmpty(locationElement);
        });

        locationElement.click(function() {
            if (locationElement.val() == emptyTip) {
                locationElement.val("");
                removeEmptyTip(locationElement);
            }
        });

        addTipIfEmpty(locationElement);
        
        function addTipIfEmpty(locationInput) {
            if (locationInput.val() == '') {
                locationInput.val(emptyTip);
                locationInput.addClass('empty');
            }
        }

        function removeEmptyTip(locationInput) {
            locationInput.removeClass('empty');
        }
        

    };
})(jQuery);

(function($) {
    $.fn.lastUsedLocationList = function(onSelectedCallback, getLastUsedLocationsCallback) {
        var locationElement = $(this);
        var locationView = new LastUsedLocationExtension(locationElement, onSelectedCallback, getLastUsedLocationsCallback);
        locationView.init();
        locationView._removeEmptyTip();
    };

})(jQuery);


function LastUsedLocationExtension(locationInput, onSelectedCallback, getLastUsedLocationsCallback) {
    this._dom = locationInput.parent();
    this._locationInput = locationInput;
    
    var title = i18n("LABEL_SELECT_LAST_USED_LOCATION");
    this._lastUsedLocationsButton = $("<span class='last_used_locations_button' title='" + title + "'>&nbsp;</span>");
    
    this._lastUsedLocationsView = $("<div class='last_used_locations hidden'><p></p><ul></ul></div>");
    this._lastUsedLocationsList = $('ul', this._lastUsedLocationsView);

    this._onSelectedCallback = onSelectedCallback;
    this._getLastUsedLocationsCallback = getLastUsedLocationsCallback;
}

LastUsedLocationExtension.prototype = {
    init: function() {
        $('p', this._lastUsedLocationsView).html(i18n('LAST_USED_LOCATIONS'));
        this._dom.append(this._lastUsedLocationsView);
        this._lastUsedLocationsButton.insertAfter(this._locationInput);
        this._bindEvents();
    },

    _bindEvents: function() {
        var me = this;

        $('body').click(function() {
            me._hideLastUsedLocations();
        });

        this._lastUsedLocationsButton.click(function(e) {
            e.stopPropagation();
            e.preventDefault();

            if (me._lastUsedLocationsView.hasClass('hidden'))
            {
                me._lastUsedLocationsList.html("");

                var lastUsedLocations = [];
                if ($.isFunction(me._getLastUsedLocationsCallback)) {
                    lastUsedLocations = me._getLastUsedLocationsCallback();
                }

                me._createLastUsedLocationItems(lastUsedLocations);
                me._setStyle();
                me._hideOtherLastUsedLocations();
                me._showLastUsedLocations();
            } else {
                me._hideLastUsedLocations();
            }
        });
    },

    _hideLastUsedLocations: function() {
        this._lastUsedLocationsView.addClass("hidden");
    },

    _showLastUsedLocations: function() {
        this._lastUsedLocationsView.removeClass("hidden");
    },

    _hideOtherLastUsedLocations: function() {
        $('.last_used_locations').addClass('hidden');
    },

    _removeEmptyTip: function() {
        this._locationInput.removeClass('empty');
        this._locationInput.val('');
        this._locationInput.tipAdded = false;
    },

    _setStyle: function() {
        this._lastUsedLocationsView.css('width', this._locationInput.width() + 20);

        //following 4 lines is to fix z-index problem in IE
        var zIndex = 2000;
        $('.location_container').each(function(i, container) {
            $(container).css('z-index', zIndex - i);
        })
    },

    _createLastUsedLocationItems : function(lastUsedLocations) {
        var me = this;
        lastUsedLocations.foreach(function(location, index) {
            var lastUsedLocationItem = $('<li></li>');
            lastUsedLocationItem.attr('index', index + 1);
            lastUsedLocationItem.html(location.fullname);
            lastUsedLocationItem.click(function() {
                me._removeEmptyTip();
                me._locationInput.val(location.fullname);
                me._lastUsedLocationsView.addClass("hidden");
                if ($.isFunction(me._onSelectedCallback)) {
                    me._onSelectedCallback(location);
                }
            });
            me._lastUsedLocationsList.append(lastUsedLocationItem);
        });
    }
};

